package android.slc.ruoyi.utils;

import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.IterableUtils;

import java.util.List;

public class PageUtils {

    public static <T> void pagination(PageInfo<T> page, List<T> list) {
        if (page != null && !IterableUtils.isEmpty(list)) {
            page.setTotal(list.size());
            judgePageBoundary(page);
            if (page.getSize() >= page.getTotal()) {
                page.setList(list);
                return;
            }
            int fromIndex = (page.getPageNum() - 1) * page.getSize();
            int toIndex = fromIndex + page.getSize();
            if (fromIndex >= page.getTotal()) {
                return;
            }
            if (toIndex > page.getTotal()) {
                toIndex = (int) page.getTotal();
            }
            page.setList(list.subList(fromIndex, toIndex));
        }
    }

    public static <I, O> PageInfo<O> pageTransformPage(PageInfo<I> page) {
        return pageTransformPage(page.getPageNum(), page.getSize(), page.getTotal());
    }

    public static <T> PageInfo<T> pageTransformPage(int current, int size, long total) {
        PageInfo<T> page = new PageInfo<>();
        page.setSize(size);
        page.setPageNum(current);
        page.setTotal(total);
        judgePageBoundary(page);
        return page;
    }

    public static <T> PageInfo<T> pageTransformPage(int current, int size, List<T> record) {
        PageInfo<T> page = new PageInfo<>();
        page.setSize(size);
        page.setPageNum(current);
        pagination(page, record);
        return page;
    }

    private static <T> void judgePageBoundary(PageInfo<T> pageInfo) {
        pageInfo.setIsFirstPage(pageInfo.getPageNum() == 1);
        pageInfo.setIsLastPage(pageInfo.getPageNum() == pageInfo.getPages() || pageInfo.getPages() == 0);
        pageInfo.setHasPreviousPage(pageInfo.getPageNum() > 1);
        pageInfo.setHasNextPage(pageInfo.getPageNum() < pageInfo.getPages());
    }
}
